package com.example.forum.services.impl;

import com.example.forum.common.AppResult;
import com.example.forum.common.ResultCode;
import com.example.forum.dao.ArticleMapper;
import com.example.forum.exception.ApplicationException;
import com.example.forum.model.Article;
import com.example.forum.model.Board;
import com.example.forum.model.User;
import com.example.forum.services.IArticleService;
import com.example.forum.services.IBoardService;
import com.example.forum.services.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @Author: wenjingyuan
 * @Date: 2023/09/24/21:04
 * @Description:
 */
@Service
@Slf4j
public class ArticleServiceImpl implements IArticleService {
    @Resource
    private ArticleMapper articleMapper;
    //用户和板块的操作
    @Resource
    private IBoardService boardService;
    @Resource
    private IUserService userService;

    /**
     * 发布帖子
     * @param article
     */
    @Override
    public void Create(Article article) {
        //首先进行参数检验
        if(article==null || article.getUserId()==null||article.getBoardId()==null
        || StringUtils.isEmpty(article.getTitle())||StringUtils.isEmpty(article.getContent())){
           //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
          //抛出异常
            throw  new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //设置默认值
        article.setVisitCount(0);
        article.setLikeCount(0);
        article.setReplyCount(0);
        article.setState((byte) 0);
        article.setDeleteState((byte) 0);
        Date date=new Date();
        article.setCreateTime(date);
        article.setUpdateTime(date);
        //数据库新增
        int row = articleMapper.insertSelective(article);
        if(row!=1){
            log.warn(ResultCode.FAILED_CREATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }

        //获取用户的操作
        User user=userService.selectById(article.getUserId());
        if(user==null){
            //打印日志
            log.info(ResultCode.ERROR_IS_NULL.toString()+", 发贴失败, user id = " + article.getUserId());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_IS_NULL));
        }
        //更新用户的发帖数
        userService.addOneArticleCountById(user.getId());

        //获取板块的操作
        Board board = boardService.selectById(article.getBoardId());
        if(board==null){
            //打印日志
            log.info(ResultCode.ERROR_IS_NULL.toString()+", 发贴失败, board id = " + article.getBoardId());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_IS_NULL));
        }
        //更新板块帖子数
        boardService.addOneArticleCountById(board.getId());
        //成功
        //打印日志
        log.info(ResultCode.SUCCESS.toString()+", user id = " + article.getUserId()
                + ", board id = " + article.getBoardId() + ", article id = "+article.getId()+"发帖成功");
       // throw new ApplicationException(AppResult.failed("测试回滚"));
    }

    @Override
    public List<Article> selectAll() {
        //调用DAO
        List<Article> articles = articleMapper.selectAll();
        //返回结果
        return articles;
    }

    @Override
    public List<Article> selectAllByBoardId(Long boardId) {
        //参数校验
        if(boardId==null || boardId<=0){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //检验板块是否存在
        Board board = boardService.selectById(boardId);
        if(board==null){
            //打印日志
            log.warn(ResultCode.FAILED_BOARD_NOT_EXISTS.toString()+"board id:"+boardId);
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_BOARD_NOT_EXISTS));
        }
        //调用DAO
        List<Article> articles = articleMapper.selectAllByBoardId(boardId);
        //返回结果
        return articles;
    }

    @Override
    public Article selectDetailById(Long id) {
        if(id==null || id<=0){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        Article article = articleMapper.selectDetailById(id);
        //检查文章是否为空
        if(article==null){
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }

        //更新访问次数
        Article updateArticle=new Article();
        updateArticle.setId(article.getId());
        updateArticle.setVisitCount(article.getVisitCount()+1);

        //调用
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if(row!=1){
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }

        //更新返回对象的访问次数
        article.setVisitCount(article.getVisitCount()+1);
        //返回对象
        return article;
    }

    @Override
    public Article selectById(Long id) {
        if(id==null || id<=0){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw  new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //调用DAO
        Article article = articleMapper.selectByPrimaryKey(id);
        return article;
    }

    @Override
    public void modify(Long id, String title, String content) {
        if(id==null || id<=0||StringUtils.isEmpty(title)||StringUtils.isEmpty(content)){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw  new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //新建一个article的对象
        Article article1=new Article();
        article1.setId(id);
        article1.setTitle(title);
        article1.setContent(content);
        article1.setUpdateTime(new Date());
        //调用DAO
        int row = articleMapper.updateByPrimaryKeySelective(article1);
        if(row!=1){
            //打印日志
            log.warn(ResultCode.ERROR_SERVICES.toString());
            //抛出异常
            throw  new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
    }

    @Override
    public void thumbsUpById(Long id) {
        //非空校验
        if(id==null || id<=0){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw  new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //通过id拿到帖子对象
        Article article = articleMapper.selectByPrimaryKey(id);
        //判断帖子不存在
        if(article==null||article.getDeleteState()==1){
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        //判断帖子是否状态异常
        if(article.getState()==1){
            log.warn(ResultCode.FAILED_ARTICLE_BANNED.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED));
        }
        //构建要更新的对象
        Article updateArticle =new Article();
        updateArticle.setId(article.getId());
        updateArticle.setVisitCount(article.getVisitCount()+1);
        updateArticle.setUpdateTime(new Date());

        //dao
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if(row!=1){
            //打印日志
            log.warn(ResultCode.ERROR_SERVICES.toString());
            //抛出异常
            throw  new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
    }

    @Override
    public void deleteById(Long id) {
        //非空校验
        if(id==null || id<=0){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw  new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //通过id拿到帖子对象
        Article article = articleMapper.selectByPrimaryKey(id);
        //判断帖子不存在
        if(article==null||article.getDeleteState()==1){
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        //构建要更新的对象
        Article updateArticle =new Article();
        updateArticle.setId(article.getId());
        updateArticle.setDeleteState((byte) 1);

        //调用DAO
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if(row!=1){
            //打印日志
            log.warn(ResultCode.ERROR_SERVICES.toString());
            //抛出异常
            throw  new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }


        //获取用户的操作
        User user=userService.selectById(article.getUserId());
        if(user==null){
            //打印日志
            log.info(ResultCode.ERROR_IS_NULL.toString()+", 删除失败, user id = " + article.getUserId());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_IS_NULL));
        }
        //更新用户的发帖数
        userService.subOneArticleCountById(user.getId());

        //获取板块的操作
        Board board = boardService.selectById(article.getBoardId());
        if(board==null){
            //打印日志
            log.info(ResultCode.ERROR_IS_NULL.toString()+", 删除失败, board id = " + article.getBoardId());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_IS_NULL));
        }
        //更新板块帖子数
        boardService.subOneArticleCountById(board.getId());
        //成功
        //打印日志
        log.info(ResultCode.SUCCESS.toString()+", user id = " + article.getUserId()
                + ", board id = " + article.getBoardId() + ", article id = "+article.getId()+"删除成功");
        // throw new ApplicationException(AppResult.failed("测试回滚"));
    }

    @Override
    public void addOneReplyCountById(Long id) {
        //非空校验
        if(id==null || id<=0){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw  new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //通过id拿到帖子对象
        Article article = articleMapper.selectByPrimaryKey(id);
        //判断帖子不存在
        if(article==null||article.getDeleteState()==1){
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        //判断帖子是否状态异常
        if(article.getState()==1){
            log.warn(ResultCode.FAILED_ARTICLE_BANNED.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED));
        }

        //构建要更新的对象
        Article updateArticle =new Article();
        updateArticle.setId(article.getId());
        //回复数加一
        updateArticle.setReplyCount(article.getReplyCount()+1);
        updateArticle.setUpdateTime(new Date());
        //调用DAO
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if(row!=1){
            //打印日志
            log.warn(ResultCode.ERROR_SERVICES.toString());
            //抛出异常
            throw  new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }

    }

    @Override
    public List<Article> selectByUserId(Long userId) {
        if(userId==null || userId<=0){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw  new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //判断user存在与否
        User user = userService.selectById(userId);
        if(user==null){
            //打印日志
            log.info(ResultCode.ERROR_IS_NULL.toString()+",  user id = " +userId);
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_IS_NULL));
        }
        //调用DAO
        List<Article> articles = articleMapper.selectByUserId(userId);
        return articles;
    }
}
